package ip.command;
/***********************************************************************
 * Module:  CreateMovieCommand.java
 * Author:  mojsilo
 * Purpose: Defines the Class CreateMovieCommand
 ***********************************************************************/

import ip.dto.MovieDTO;
import ip.ejb.session.facade.MovieFacadeLocal;
import ip.ejb.session.facade.MovieFacadeLocalHome;
import ip.exceptions.CanNotCreateNewMovieException;
import ip.exceptions.UnexpectedException;
import ip.util.EJBHomeFactory;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

public class CreateMovieCommand extends Command
{
	private MovieDTO movieDTO;
	private MovieFacadeLocal movieFacadeLocal;
	private Logger logger = Logger.getLogger(this.getClass());

	public void init() throws UnexpectedException{
		try {
			logger.debug("init()");
			MovieFacadeLocalHome movieFacadeLocalHome = (MovieFacadeLocalHome) EJBHomeFactory.getInstance().createLocalHome(ip.ejb.session.facade.MovieFacadeLocalHome.class);
			movieFacadeLocal = movieFacadeLocalHome.create();
			
		} catch (NamingException e) {
			e.printStackTrace();
			logger.error(e);
			throw new UnexpectedException();			
		} catch (CreateException e) {
			e.printStackTrace();
			logger.error(e);
			throw new UnexpectedException();			
		}

	}

	public void execute() throws UnexpectedException,CanNotCreateNewMovieException{
		try {
			logger.debug("execute()");
			movieFacadeLocal.createMovie(movieDTO);
		} catch (CanNotCreateNewMovieException e) {
			logger.error(e);
			e.printStackTrace();
			throw new CanNotCreateNewMovieException(movieDTO);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			throw new UnexpectedException();			
		}
	}

	public void dispose() throws UnexpectedException{
		try {
			logger.debug("dispose()");
			movieFacadeLocal.remove();

		} catch (EJBException e) {					
			e.printStackTrace();
			logger.error(e);
			throw new UnexpectedException();
		} catch (RemoveException e) {		
			e.printStackTrace();
			logger.error(e);
			throw new UnexpectedException();
		}
	}

	public void setMovieDTO(MovieDTO movieDTO)
	{
		this.movieDTO = movieDTO;
	}

}